package xin.mydreams.mybill.widget.home.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import com.fasterxml.jackson.annotation.JsonFormat;

import lombok.Getter;
import lombok.Setter;
import xin.mydreams.mybill.util.UserUtil;
import xin.mydreams.mybill.widget.user.entity.User;

/**
 * 系统实体对象抽象类<br>
 * 包含主键id，子类不需要定义主键
 * 
 * @Type BaseEntity.java
 * @Desc
 * @mail guzehao@mydreams.xin
 * @author 谷泽昊
 * @date 2019年1月29日 下午9:10:00
 * @version
 */
@Getter
@Setter
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
	private static final long serialVersionUID = -2955330485748809219L;

	@Id
	@Column(name = "`id`",length=50)
	private String id;

	/**
	 * 对象创建时间
	 */
	@Column(name = "`created_time`", updatable = false)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date createdTime;

	/**
	 * 创建用户
	 */
	@ManyToOne
	@JoinColumn(name = "created_user")
	private User createdUser;

	/**
	 * 最后修改时间
	 */
	@Column(name = "`last_modified_time`")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	private Date lastModifiedTime;

	/**
	 * 最后修改用户
	 */
	@ManyToOne
	@JoinColumn(name = "last_modified_user")
	private User lastModifiedUser;

	@PrePersist
	protected void onCreate() {
		if (id == null) {
			id = UUID.randomUUID().toString().replace("-", "");
		}

		createdTime = new Date();
		if (UserUtil.getUser() != null) {
			createdUser = UserUtil.getUser();
		}
	}

	@PreUpdate
	protected void onUpdate() {
		lastModifiedTime = new Date();
		if (UserUtil.getUser() != null) {
			lastModifiedUser = UserUtil.getUser();
		}
	}
}
